package com.dhh.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;
import com.dhh.R;
import com.dhh.dao.DataBaseHelper;
import com.dhh.util.CUtil;
import com.dhh.util.Constant;
import com.dhh.util.StringUtil;
import com.dhh.util.manager.FoodLogManager;
import com.dhh.util.manager.PlanManager;
import com.dhh.vo.Food;
import com.dhh.vo.FoodLog;
import com.dhh.vo.FoodPlan;
import com.dhh.vo.PlanItem;
import com.dhh.widget.AmazingAdapter;
import com.dhh.widget.AmazingListView;
import greendroid.app.GDActivity;

public class FoodLogDetailActivity extends GDActivity{	
	private DataBaseHelper db;
	private AmazingListView lsComposer;
	private String cItemId;
	private FoodLogManager fManager;
	private PlanManager pManager;
	private FoodPlan plan;
	private Map<String,List<FoodLog>> logs;
	private String date;
	
	
	@Override
    public void onCreate(Bundle intent){
        super.onCreate(intent);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setActionBarContentView(R.layout.make_plan);
		
        db = new DataBaseHelper(getBaseContext());
        db.openDataBase();
        fManager = new FoodLogManager(db); 		
        pManager = new PlanManager(db); 
        
        date = getIntent().getExtras().getString(Constant.C_LOG_DATE);
        
        String title = "My Log   "+CUtil.getDate("yyyy-MM-dd", "EEE,MMM dd", date);
        getActionBar().setTitle(title);
        getActionBar().setBackgroundColor(Color.rgb(14, 166, 249));
        getActionBar().getChildAt(0).
        	setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(FoodLogDetailActivity.this,HomeActivity.class);	
					startActivity(intent);
				}}); 
        
        lsComposer = (AmazingListView) findViewById(R.id.lsComposer);
		lsComposer.setDivider( null );
		lsComposer.setDividerHeight(1); 
		lsComposer.setPinnedHeaderView(LayoutInflater.from(this).inflate(R.layout.fp_items, lsComposer, false));
		lsComposer.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {				
				cItemId = ((TextView) view.findViewById(R.id.fp_item_id)).getText().toString();
				FoodLogDetailActivity.this.showDialog(0);
				
				return true;
			}
		});
  	}
	
	@Override
	public void onStart() {
        super.onStart();

		fillData();		
    }
	
	private void fillData(){
		logs = fManager.getLog(date);
		plan = pManager.getCurrentPlanSimple();
		initFoodGroup();
		lsComposer.setAdapter(new SectionComposerAdapter());
		((TextView)findViewById(R.id.mp_plan_grain_c)).setText(String.valueOf(cGrain));
		((TextView)findViewById(R.id.mp_plan_fruit_c)).setText(String.valueOf(cFruit));
		((TextView)findViewById(R.id.mp_plan_vegetable_c)).setText(String.valueOf(cVegetable));
		((TextView)findViewById(R.id.mp_plan_dairy_c)).setText(String.valueOf(cDairy));
		((TextView)findViewById(R.id.mp_plan_protein_c)).setText(String.valueOf(cProtein));
		
		String pe = getPlanEnergy(logs)!=null ? getPlanEnergy(logs):plan.getEnergy();
		((TextView)findViewById(R.id.mp_plan_energy_t)).setText(pe);
		((TextView)findViewById(R.id.mp_plan_energy_c)).setText(String.valueOf(cEnergy));
	}
	
	private String getPlanEnergy(Map<String, List<FoodLog>> map){
		String energy = null;
		if(map.get(PlanItem.PERIOD_BREAKFAST).size()>0){
			energy = map.get(PlanItem.PERIOD_BREAKFAST).get(0).getPlanEnergy();
		}else if(map.get(PlanItem.PERIOD_LUNCH).size()>0){
			energy = map.get(PlanItem.PERIOD_LUNCH).get(0).getPlanEnergy();
		}else if(map.get(PlanItem.PERIOD_DINNER).size()>0){
			energy = map.get(PlanItem.PERIOD_DINNER).get(0).getPlanEnergy();
		}else if(map.get(PlanItem.PERIOD_SNACK).size()>0){
			energy = map.get(PlanItem.PERIOD_SNACK).get(0).getPlanEnergy();
		}
		
		return energy;
	}
	
	private Long cGrain;
	private Long cFruit;
	private Long cVegetable;
	private Long cProtein;
	private Long cDairy;
	private Long cEnergy;
	private void initFoodGroup(){
		cGrain = 0l;
		cVegetable = 0l;
		cProtein = 0l;
		cDairy = 0l;
		cFruit = 0l;
		cEnergy = 0l;
		List<FoodLog> ls = new ArrayList<FoodLog>();
		ls.addAll(logs.get(PlanItem.PERIOD_BREAKFAST));
		ls.addAll(logs.get(PlanItem.PERIOD_LUNCH));
		ls.addAll(logs.get(PlanItem.PERIOD_DINNER));
		ls.addAll(logs.get(PlanItem.PERIOD_SNACK));
		
		for(FoodLog l : ls){
			if(Food.FOOD_GROUP_GRAIN.equals(l.getFoodGroup())){
				cGrain += Long.parseLong(l.getQuatity());
			}else if(Food.FOOD_GROUP_FRUIT.equals(l.getFoodGroup())){
				cFruit += Long.parseLong(l.getQuatity());	
			}else if(Food.FOOD_GROUP_VEGETABLE.equals(l.getFoodGroup())){
				cVegetable += Long.parseLong(l.getQuatity());	
			}else if(Food.FOOD_GROUP_PROTEIN.equals(l.getFoodGroup())){
				cProtein += Long.parseLong(l.getQuatity());		
			}else if(Food.FOOD_GROUP_DAIRY.equals(l.getFoodGroup())){
				cDairy += Long.parseLong(l.getQuatity());
			}
			
			cEnergy += Long.parseLong(l.getEnergy());
		}
	}
	
	@Override
    public void onResume(){
    	super.onResume();
        db.openDataBase();       
    }
    
    @Override
	protected void onPause(){
		super.onPause();
		if (db != null) {
			db.close();
		}
	}
    
    @Override
	protected void onStop(){
		super.onStop();
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch(id){
		case 0:
			return new AlertDialog.Builder(this)
			.setIcon(android.R.drawable.ic_dialog_alert)
			.setTitle("Are you sure you want to delete this food?")
			.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,	int whichButton){
						fManager.deleteFoodLog(cItemId);
						FoodLogDetailActivity.this.fillData();
						Toast.makeText(getBaseContext(),"The food has been deleted!", Toast.LENGTH_SHORT).show();
					}
				}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,int whichButton){
								//Toast.makeText(getBaseContext(),"Cancel clicked!", Toast.LENGTH_SHORT).show();
						}
					}).create();
		}
		
		return null;
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List<Pair<String, List<FoodLog>>>  getAllData(){
		List<Pair<String, List<FoodLog>>>  lst = new ArrayList<Pair<String, List<FoodLog>>>();
		Pair bPair = new Pair(PlanItem.PERIOD_BREAKFAST,logs.get(PlanItem.PERIOD_BREAKFAST));
		Pair lPair = new Pair(PlanItem.PERIOD_LUNCH,logs.get(PlanItem.PERIOD_LUNCH));
		Pair dPair = new Pair(PlanItem.PERIOD_DINNER,logs.get(PlanItem.PERIOD_DINNER));
		Pair daPair = new Pair(PlanItem.PERIOD_SNACK,logs.get(PlanItem.PERIOD_SNACK));
		lst.add(bPair);
		lst.add(lPair);
		lst.add(dPair);
		lst.add(daPair);
		return lst;
	}
	
	class SectionComposerAdapter extends AmazingAdapter {
		List<Pair<String, List<FoodLog>>> all = getAllData();

		@Override
		public int getCount() {
			int res = 0;
			for (int i = 0; i < all.size(); i++) {
				res += all.get(i).second.size();
			}
			return res;
		}

		@Override
		public FoodLog getItem(int position) {
			int c = 0;
			for (int i = 0; i < all.size(); i++) {
				if (position >= c && position < c + all.get(i).second.size()) {
					return all.get(i).second.get(position - c);
				}
				c += all.get(i).second.size();
			}
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		protected void onNextPageRequested(int page) {
		}

		@Override
		protected void bindSectionHeader(View view, int position, boolean displaySectionHeader) {
			if (displaySectionHeader) {
				view.findViewById(R.id.header).setVisibility(View.VISIBLE);
				TextView lSectionTitle = (TextView) view.findViewById(R.id.header);
				lSectionTitle.setText(getSections()[getSectionForPosition(position)]);
			} else {
				view.findViewById(R.id.header).setVisibility(View.GONE);
			}
		}

		@Override
		public View getAmazingView(int position, View convertView, ViewGroup parent) {
			View res = convertView;
			if (res == null) res = getLayoutInflater().inflate(R.layout.item_composer, null);
			TextView foodName = (TextView) res.findViewById(R.id.fp_foodname);
			TextView foodGroup = (TextView) res.findViewById(R.id.fp_foodgroup);
			TextView service = (TextView) res.findViewById(R.id.fp_service);
			TextView calorie = (TextView) res.findViewById(R.id.fp_calorie);
			TextView itemId = (TextView) res.findViewById(R.id.fp_item_id);
			
			FoodLog item = getItem(position);
			foodName.setText(StringUtil.cutString(item.getFoodName(),40));
			foodGroup.setText(item.getFoodGroup()+",");
			service.setText(item.getQuatity()+" g,");
			calorie.setText(item.getEnergy()+" cals");
			itemId.setText(item.getId());
			
			return res;
		}

		@Override
		public void configurePinnedHeader(View header, int position, int alpha) {
			TextView lSectionHeader = (TextView)header;
			lSectionHeader.setText(getSections()[getSectionForPosition(position)]);
			lSectionHeader.setBackgroundColor(alpha << 24 | (0xbbffbb));
			lSectionHeader.setTextColor(alpha << 24 | (0x000000));
		}

		@Override
		public int getPositionForSection(int section) {
			if (section < 0) section = 0;
			if (section >= all.size()) section = all.size() - 1;
			int c = 0;
			for (int i = 0; i < all.size(); i++) {
				if (section == i) { 
					return c;
				}
				c += all.get(i).second.size();
			}
			return 0;
		}

		@Override
		public int getSectionForPosition(int position) {
			int c = 0;
			for (int i = 0; i < all.size(); i++) {
				if (position >= c && position < c + all.get(i).second.size()) {
					return i;
				}
				c += all.get(i).second.size();
			}
			return -1;
		}

		@Override
		public String[] getSections() {
			String[] res = new String[all.size()];
			for (int i = 0; i < all.size(); i++) {
				res[i] = all.get(i).first;
			}
			return res;
		}
		
	}

}
